<template>
  <el-dialog
    title="跨学期复制考核方案"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="cross-term-copy-content">
      <!-- 源教学任务信息 -->
      <el-card v-if="sourceMission" class="source-card" style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <span>源考核方案</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程名称">{{ sourceMission.courseName }}</el-descriptions-item>
          <el-descriptions-item label="课程编码">{{ sourceMission.courseCode }}</el-descriptions-item>
          <el-descriptions-item label="学期">{{ sourceMission.termName }}</el-descriptions-item>
          <el-descriptions-item label="教师">
            <span v-if="sourceMission.teacherNames && sourceMission.teacherNames.length > 0">
              {{ sourceMission.teacherNames.join(', ') }}
            </span>
            <span v-else>未分配</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 源考核方案详情 -->
        <div v-if="sourceExamParts.length > 0" style="margin-top: 15px;">
          <h4 style="margin: 10px 0; color: #303133; font-size: 14px;">考核方案组成：</h4>
          <el-table :data="sourceExamParts" size="small" border>
            <el-table-column prop="name" label="考核组成" width="120" />
            <el-table-column prop="proportion" label="比例" width="80">
              <template #default="scope">{{ scope.row.proportion }}%</template>
            </el-table-column>
            <el-table-column prop="scoreTypeName" label="计分方式" width="100" />
            <el-table-column label="考核类型" width="90">
              <template #default="scope">
                <el-tag 
                  v-if="scope.row.examPartType === 'FORMATIVE'" 
                  type="success" 
                  size="small"
                >
                  形成性
                </el-tag>
                <el-tag 
                  v-else-if="scope.row.examPartType === 'FINAL'" 
                  type="warning" 
                  size="small"
                >
                  终结性
                </el-tag>
                <el-tag v-else type="info" size="small">其它</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 目标学期选择和教学任务选择 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>选择目标教学任务</span>
            <div class="header-actions">
              <el-select 
                v-model="selectedTermId" 
                placeholder="选择学期" 
                @change="loadTargetMissions"
                style="width: 200px; margin-right: 10px;"
              >
                <el-option label="全部学期" :value="null" />
                <el-option 
                  v-for="term in availableTerms" 
                  :key="term.id" 
                  :label="term.name" 
                  :value="term.id"
                />
              </el-select>
              <el-checkbox 
                v-model="selectAll" 
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              >
                全选
              </el-checkbox>
              <span class="selected-count">已选择 {{ selectedTargets.length }} 个</span>
            </div>
          </div>
        </template>

        <div v-loading="loadingTargets">
          <el-alert
            v-if="targetMissions.length === 0 && !loadingTargets"
            title="没有找到可复制的目标教学任务"
            description="该课程在其他学期没有教学任务，或所有教学任务都已设置考核方案。"
            type="info"
            :closable="false"
            show-icon
          />

          <el-checkbox-group v-model="selectedTargets" v-if="targetMissions.length > 0">
            <div class="missions-grid">
              <el-card 
                v-for="mission in targetMissions" 
                :key="mission.id"
                class="mission-card"
                :class="{ 'selected': selectedTargets.includes(mission.id) }"
                shadow="hover"
              >
                <div class="mission-checkbox">
                  <el-checkbox :label="mission.id">
                    <div class="mission-info">
                      <div class="mission-title">{{ mission.courseName }}</div>
                      <div class="mission-details">
                        <div>课程编码：{{ mission.courseCode }}</div>
                        <div>学期：{{ mission.termName }}</div>
                        <div>教师：{{ mission.teacherNames?.join(', ') || '未分配' }}</div>
                        <div>学员：{{ mission.studentCount || 0 }}人</div>
                        <div v-if="mission.hasExamParts" class="has-exam-parts">
                          <el-tag type="warning" size="small">已设置考核组成</el-tag>
                          <span class="overwrite-hint">（将被覆盖）</span>
                        </div>
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </el-card>
            </div>
          </el-checkbox-group>
        </div>
      </el-card>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCrossTermCopy"
          :disabled="selectedTargets.length === 0"
          :loading="copying"
        >
          跨学期复制
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { courseExamPartApi } from '@/api/course-exam-part'
import { teachingMissionApi } from '@/api/teaching-mission'
import { termApi } from '@/api/base-data'

export default {
  name: 'CrossTermCopyDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    sourceMissionId: {
      type: Number,
      default: null
    }
  },
  emits: ['update:visible', 'completed'],
  setup(props, { emit }) {
    const sourceMission = ref(null)
    const sourceExamParts = ref([])
    const targetMissions = ref([])
    const availableTerms = ref([])
    const selectedTargets = ref([])
    const selectedTermId = ref(null)
    
    const loadingTargets = ref(false)
    const copying = ref(false)
    
    // 计算属性
    const selectAll = computed({
      get: () => {
        return targetMissions.value.length > 0 && selectedTargets.value.length === targetMissions.value.length
      },
      set: (value) => {
        if (value) {
          selectedTargets.value = targetMissions.value.map(m => m.id)
        } else {
          selectedTargets.value = []
        }
      }
    })
    
    const isIndeterminate = computed(() => {
      const selected = selectedTargets.value.length
      const total = targetMissions.value.length
      return selected > 0 && selected < total
    })
    
    // 方法
    const loadSourceMission = async () => {
      if (!props.sourceMissionId) return
      
      try {
        // 获取源教学任务信息
        sourceMission.value = await teachingMissionApi.getTeachingMissionById(props.sourceMissionId)
        
        // 获取源考核组成
        sourceExamParts.value = await courseExamPartApi.getExamPartsByTeachingMission(props.sourceMissionId)
      } catch (error) {
        console.error('加载源教学任务失败:', error)
        ElMessage.error('加载源教学任务失败')
      }
    }
    
    const loadAvailableTerms = async () => {
      try {
        const terms = await termApi.getAllTerms()
        // 排除当前源教学任务的学期
        availableTerms.value = terms.filter(term => 
          term.id !== sourceMission.value?.termId
        )
        
        // 默认选择当前学期
        const currentTerm = availableTerms.value.find(term => term.isCurrent)
        if (currentTerm) {
          selectedTermId.value = currentTerm.id
        }
      } catch (error) {
        console.error('加载学期数据失败:', error)
        ElMessage.error('加载学期数据失败')
      }
    }
    
    const loadTargetMissions = async () => {
      if (!props.sourceMissionId) return
      
      loadingTargets.value = true
      try {
        const missions = await courseExamPartApi.getCrossTermTargetMissionsForCopy(
          props.sourceMissionId, 
          selectedTermId.value
        )
        targetMissions.value = missions
        selectedTargets.value = []
      } catch (error) {
        console.error('加载目标教学任务失败:', error)
        ElMessage.error('加载目标教学任务失败')
      } finally {
        loadingTargets.value = false
      }
    }
    
    const handleSelectAll = (value) => {
      selectAll.value = value
    }
    
    const handleCrossTermCopy = async () => {
      if (selectedTargets.value.length === 0) {
        ElMessage.warning('请选择目标教学任务')
        return
      }
      
      try {
        const hasExistingExamParts = targetMissions.value.some(mission => 
          selectedTargets.value.includes(mission.id) && mission.hasExamParts
        )
        
        let confirmMessage = `确定要复制考核方案到选中的 ${selectedTargets.value.length} 个教学任务吗？`
        if (hasExistingExamParts) {
          confirmMessage += '\n\n注意：部分目标教学任务已设置考核组成，将被覆盖！'
        }
        
        await ElMessageBox.confirm(
          confirmMessage,
          '确认跨学期复制',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        copying.value = true
        
        await courseExamPartApi.copyExamPartsToOtherMissions(props.sourceMissionId, selectedTargets.value)
        
        ElMessage.success('跨学期复制考核方案成功')
        emit('completed')
        handleClose()
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('跨学期复制失败:', error)
          ElMessage.error('跨学期复制失败')
        }
      } finally {
        copying.value = false
      }
    }
    
    const handleClose = () => {
      emit('update:visible', false)
      // 重置数据
      sourceMission.value = null
      sourceExamParts.value = []
      targetMissions.value = []
      selectedTargets.value = []
      selectedTermId.value = null
    }
    
    // 监听器
    watch(() => props.visible, async (newValue) => {
      if (newValue && props.sourceMissionId) {
        await loadSourceMission()
        await loadAvailableTerms()
        await loadTargetMissions()
      }
    })
    
    return {
      sourceMission,
      sourceExamParts,
      targetMissions,
      availableTerms,
      selectedTargets,
      selectedTermId,
      loadingTargets,
      copying,
      selectAll,
      isIndeterminate,
      
      loadTargetMissions,
      handleSelectAll,
      handleCrossTermCopy,
      handleClose
    }
  }
}
</script>

<style scoped>
.cross-term-copy-content {
  max-height: 600px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  font-size: 14px;
  color: #909399;
  white-space: nowrap;
}

.missions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.mission-card {
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.mission-card.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.mission-card:hover {
  border-color: #c6e2ff;
}

.mission-checkbox {
  width: 100%;
}

.mission-info {
  width: 100%;
}

.mission-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-bottom: 8px;
}

.mission-details {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.mission-details > div {
  margin-bottom: 4px;
}

.has-exam-parts {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.overwrite-hint {
  font-size: 12px;
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>